/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fserver.core;

import constan.Config;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author LINHNC
 */
public class CoreServer {

    private static CoreServer instance;

    // init data for connect begin
    private ServerSocket server;
    private List<Socket> listClient;
    // init data for connect end

    // controler server run/stop
    private boolean isRunning;

    private CoreServer() {
        try {
            listClient = new ArrayList<Socket>();
            server = new ServerSocket(constan.Config.SERVER_PORT);
            isRunning = true;
        } catch (IOException ex) {
            isRunning = false;
            System.out.println("Can't not start server at port: " + Config.SERVER_PORT);
            Logger.getLogger(CoreServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static CoreServer getInstance() {
        if (instance == null) {
            instance = new CoreServer();
        }
        return instance;
    }

    // TODO do work here
    public void startServer() {
        //1) start : accept
        Thread pool = new Thread(new  Runnable() {
            @Override
            public void run() {
                acceptClient();
            }
        });
        pool.start();
        
        
        
        //2) communication with client;
        
    }

    private void acceptClient() {
        Socket clientItem;
        while (isRunning) {
            try {
                clientItem = server.accept();
                synchronized (listClient) {
                    listClient.add(clientItem);
                }
            } catch (IOException ex) {
                System.out.println("can't not accept client connected!: CoreServer.java");
                Logger.getLogger(CoreServer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void commuincation() {
        
    }
}
